<template>
  <div>
    <div class="container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>登录</span>
        </div>
        <el-form
          :model="loginForm"
          :rules="loginRules"
          label-width="100px"
          ref="loginFormRef"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input prefix-icon="el-icon-user" v-model="loginForm.userName" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input prefix-icon="el-icon-lock" type="password" v-model="loginForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('loginFormRef')">提交</el-button>
            <el-button @click="resetForm('loginFormRef')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loginForm: {
        userName: "admin",
        password: "admin"
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          await this.$http
            .post("/api/login", this.loginForm)
            .then(res => {
              const result = res.data;
              if (result.code == 0) {
                this.$message({
                  message: "登录成功",
                  type: "success"
                });
                window.sessionStorage.setItem("token", result.data.token);
                this.$router.push("/home");
              } else {
                this.$message({
                  message: "登录失败",
                  type: "error"
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    valid() {
      alert(111);
    }
  }
};
</script>
<style lang="less" scoped>
.container {
  width: 450px;
  height: 300px;
  align-content: center;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 480px;
}
</style>